package com.example.repeatsubmit.policy.conretepolicy;

import com.example.repeatsubmit.exception.RepeatSubmitException;
import com.example.repeatsubmit.policy.RepeatPolicy;
import com.example.repeatsubmit.utils.ApplicationContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author caoqianhuan
 * @date 2022/8/22
 * @Description:
 */
public class RedisTimeOutRefuse extends RepeatPolicy {
    private StringRedisTemplate stringRedisTemplate;

    public RedisTimeOutRefuse() {
    }
    @Override
    public boolean isRepeatSubmit(HttpServletRequest servletRequest) {
        if (stringRedisTemplate == null) {
            stringRedisTemplate = (StringRedisTemplate) ApplicationContextUtil.getBean("stringRedisTemplate");
        }

        String preRequestKey = getLastRequest(servletRequest);
        System.out.printf(preRequestKey);
        String requestFlag = stringRedisTemplate.opsForValue().get(preRequestKey);
        if (requestFlag != null) {
            return true;
        }
        stringRedisTemplate.opsForValue().set(preRequestKey, REPEAT_SUBMIT_FLAG, interval, TimeUnit.MILLISECONDS);
        return false;
    }
}
